package com.ctrip.demo.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class LeetCode589 {

    public static void main(String[] args) {


    }

    public List<Integer> preorder(Node root) {
        List<Integer> res = new ArrayList<>();
        Deque<Object[]> deque = new ArrayDeque<>();
        deque.addLast(new Object[]{root, 0});
        while (!deque.isEmpty()) {
            Object[] pool = deque.pollLast();
            Node node = (Node) pool[0];
            Integer cnt = (Integer) pool[1];
            if (node == null) {
                continue;
            }
            if (cnt == 0) {
                res.add(node.val);
            }
            if (cnt < node.children.size()) {
                // 同一个节点
                deque.addLast(new Object[]{node, cnt + 1});
                // 当前节点的子节点
                deque.addLast(new Object[]{node.children.get(cnt), 0});
            }
        }
        return res;
    }

    public List<Integer> preorder1(Node root) {
        List<Integer> res = new ArrayList<>();
        dfs(root, res);
        return res;
    }

    private void dfs(Node root, List<Integer> res) {
        if (null == root) {
            return;
        }
        res.add(root.val);

        for (int i = 0; i < root.children.size(); i ++) {
            dfs(root.children.get(i), res);
        }
    }
}

class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
